#include "tcpProtocolWorker.h"


#include <qtcpsocket.h>
#include <QThread>
#include <QImage>

#include <QFile>
#include <QCoreApplication>
#include <glog/logging.h>

TcpProtocolWorker::TcpProtocolWorker(QObject *parent)
    : QObject{parent}, m_socket(nullptr)
{
    
}

TcpProtocolWorker::~TcpProtocolWorker()
{
    google::ShutdownGoogleLogging();
}


void TcpProtocolWorker::connectToServer(const QString &ip, quint16 port)
{
    if (m_socket)
    {
        qDebug() << "status" << m_socket->state();
        if (m_socket->state() == QAbstractSocket::ConnectedState)
        {
            return;
        }
    }
    
    if (m_ip == ip && m_port == port && m_socket && m_socket->state() == QAbstractSocket::ConnectedState) {
        qDebug() << "已经连接到目标服务器，无需重复连接";
        return;
    }

    m_ip = ip;
    m_port = port;

    if (m_socket) {
        m_socket->deleteLater();
        m_socket = nullptr;
    }
    m_socket = new QTcpSocket();

    connect(m_socket, &QTcpSocket::connected, this, &TcpProtocolWorker::connected);
    connect(m_socket, &QTcpSocket::disconnected, this, &TcpProtocolWorker::disconnected);
    connect(m_socket, &QTcpSocket::readyRead, this, &TcpProtocolWorker::onReadyRead);
    
    m_socket->connectToHost(ip, port);

    if (m_socket->waitForConnected(5000)) {
        qDebug() << "连接成功";
        emit sendProtocolConnectStatus(true);
    } else {
        emit errorOccurred(m_socket->errorString());
        qDebug() << "连接失败" << m_socket->errorString();
        emit sendProtocolConnectStatus(false);
    }
}

void TcpProtocolWorker::sendData(const QByteArray &data)
{
    qDebug() << "TcpProtocolWorker::sendData 当前线程：" << QThread::currentThreadId();
    //qDebug() << "send Data" << data.toHex().toUpper();
    if (m_socket && m_socket->state() == QAbstractSocket::ConnectedState) {
        m_socket->write(data);
        m_socket->flush();
        // 记录日志
        LOG(INFO) << "tcp Send:" << qPrintable(QString(data.toHex().toUpper()));
    } else {
        qWarning() << "Socket not connected. Cannot send data.";
    }
}



void TcpProtocolWorker::onReadyRead()
{
    //qDebug() << "TcpProtocolWorker::onReadyRead" << QThread::currentThreadId();
    QByteArray data = m_socket->readAll();
    LOG(INFO) << "recv (from tcp):" << qPrintable(QString(data.toHex().toUpper()));
    QHostAddress sender;
    emit readyReadData(data, sender);
}


